package routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producter {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置IP地址、端口号
        factory.setHost(Constants.HOST);
        factory.setPort(Constants.PORT);
        // 设置虚拟机名称
        factory.setVirtualHost(Constants.VIRTUAL_HOST);
        // 设置用户名和密码
        factory.setUsername(Constants.USER_NAME);
        factory.setPassword(Constants.USER_PASSWORD);
        // 创建连接
        Connection connection = factory.newConnection();
        // 创建 channel
        Channel channel = connection.createChannel();
        // 声明交换机
        /**
         * exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable)
         */
        channel.exchangeDeclare(Constants.ROUTING_CHANGE, BuiltinExchangeType.DIRECT, true);
        // 声明两个队列
        channel.queueDeclare(Constants.ROUTINT_QUEUE_1, true, false, false, null);
        channel.queueDeclare(Constants.ROUTINT_QUEUE_2, true, false, false, null);
        // 绑定交换机和队列
        /**
         *  queueBind(String queue, String exchange, String routingKey)
         */
        channel.queueBind(Constants.ROUTINT_QUEUE_1, Constants.ROUTING_CHANGE, "a");
        channel.queueBind(Constants.ROUTINT_QUEUE_2, Constants.ROUTING_CHANGE, "a");
        channel.queueBind(Constants.ROUTINT_QUEUE_2, Constants.ROUTING_CHANGE, "b");
        channel.queueBind(Constants.ROUTINT_QUEUE_2, Constants.ROUTING_CHANGE, "c");
        // 发送消息
        String message = "a";
        channel.basicPublish(Constants.ROUTING_CHANGE, "a", null, message.getBytes());
        String messageB = "b";
        channel.basicPublish(Constants.ROUTING_CHANGE, "b", null, messageB.getBytes());
        String messageC = "c";
        channel.basicPublish(Constants.ROUTING_CHANGE, "c", null, messageC.getBytes());

        System.out.println("消息发送完成");
        // 释放资源
        channel.close();
        connection.close();
    }
}
